#pragma once
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <sys/select.h>
#include "Socket.hpp"
#include "Mutex.hpp"
#include "Log.hpp"
#include <memory>
#include <unistd.h>
#include <arpa/inet.h>

#define MAX 4096
using namespace SocketModule;
using namespace LockModule;
using namespace LogModule;
const int defaultfd = -1;
class PollServer
{
public:
    PollServer(int port)
        : _port(port), _listen_socket(std::make_unique<TcpSocket>()), _is_running(false)
    {
    }
    void Recver(int i)
    {
        char _recv_buf[1024];
        ssize_t n = recv(_fd_arry[i], _recv_buf, sizeof(_recv_buf), 0); // 此时读写就不会被阻塞了
        if (n > 0)
        {
            _recv_buf[n] = 0;
            LOG(LogLevel::INFO) << "recv from client" << "sockfd=" << _fd_arry[i] << "msg=" << _recv_buf;
            // 回显给客户端
            std::string message = "Echo#";
            message += _recv_buf;
            send(_fd_arry[i], message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFO) << "client 正常退出 " << "sockfd=" << _fd_arry[i];
            close(_fd_arry[i]);
            _fd_arry[i] = defaultfd;
        }
        else
        {
            LOG(LogLevel::ERROR) << "recv error" << "sockfd=" << _fd_arry[i];
            close(_fd_arry[i]);
            _fd_arry[i] = defaultfd;
        }
    }
    void Accepter()
    {
        InetAddr client_addr;
        int client_sockfd = _listen_socket->Accept(&client_addr); // 这时就不会阻塞了
        if (client_sockfd < 0)
        {
            LOG(LogLevel::ERROR) << "accept error";
            return;
        }
        else
        {
            LOG(LogLevel::INFO) << "accept a client" << "new_sockfd=" << client_sockfd;
            // 此时不可以直接recv因为不确定对方有没有发数据，现在只是建立了链接
            // 所以继续select
            // 由于select返回结果会把那三个集合进行修改，所以每次调用select都要重新设置readfds这三个参数
            // 所以我们怎么知道要设置哪些文件描述符呢
            // 因此要设置一个新的集合，把历史的fd都保存起来，除非关闭了某个fd，否则一直保存着
            int pos = -1;
            for (int j = 0; j < NUM; j++)
            {
                if (_fd_arry[j] == defaultfd)
                {
                    pos = j;
                    break;
                }
            }
            if (pos == -1)
            {
                LOG(LogLevel::ERROR) << "too many clients";
                close(client_sockfd);
            }
            else
            {
                _fd_arry[pos] = client_sockfd;
            }
        }
    }
    void  Dispatcher(fd_set &fds)
    {
        for (int i = 0; i < NUM; i++)
        {
            if (_fd_arry[i] == defaultfd)
                continue;
            if (_fd_arry[i] == _listen_socket->Fd()) // 继续accept
            {
                if (FD_ISSET(_listen_socket->Fd(), &fds))
                {
                    Accepter();
                }
            }
            else
            {
                if (FD_ISSET(_fd_arry[i], &fds)) // 进行客户端和服务端的IO操作
                {
                    Recver(i);
                }
            }
        }
    }
    void Loop()
    {
        if (_is_running)
            return;
        fd_set fds;
        _is_running = true;
        while (_is_running)
        {
            int n = poll(maxfd + 1, &fds, nullptr, nullptr, &timeout);
            switch (n)
            {
            case -1:
                LOG(LogLevel::ERROR) << "select error";
                break;
            case 0:
                LOG(LogLevel::DEBUG) << "select timeout";
                break;
            default:
                LOG(LogLevel::DEBUG) << "select success";
                Dispatcher(fds);
                break;
            }
        }

        _is_running = false;
    }
    void Init()
    {
        _listen_socket->BuildTcpSocket(_port);
    }
    ~PollServer()
    {}

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _is_running;
};